package com.dingup.mock.controller.listening;

import com.dingup.api.base.HttpResContent;
import com.dingup.mock.bean.exam.ExaminationInfo;
import com.dingup.mock.bean.listening.ExamListeningInfo;
import com.dingup.mock.bean.listening.ListeningDataMapInfo;
import com.dingup.mock.bean.listening.TsListeningArticle;
import com.dingup.mock.bean.listening.TsListeningQuestion;
import com.dingup.mock.dao.listening.TsListeningArticlesMapper;
import com.dingup.mock.dao.listening.TsListeningQuestionsMapper;
import com.dingup.mock.enums.ExamContentTypeEnum;
import com.dingup.mock.module.SExaminationQueueCache;
import com.dingup.mock.util.ConstUtil;
import com.dingup.mock.util.SysUtil;
import com.suyeer.basic.util.BHttpResUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.mock.util.ConstUtil.*;

/**
 * Created by yanggavin on 16/4/9.
 */
@Controller
@RequestMapping("/listening")
public class ListeningController {
    @Autowired
    private TsListeningArticlesMapper tsListeningArticlesMapper;
    @Autowired
    private TsListeningQuestionsMapper tsListeningQuestionsMapper;


    @RequestMapping(value = "/get_data.do", method = RequestMethod.POST)
    public void getListeningAllData(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
        HttpResContent<ListeningDataMapInfo> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取听力数据");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            // do
            ListeningDataMapInfo ldmi = new ListeningDataMapInfo();
            ldmi.setSubjectName(subjectName);
            List<TsListeningArticle> articles = tsListeningArticlesMapper.getListBySubjectName(subjectName);
            if (articles.size() == 0) {
                throw new IllegalArgumentException("套题名称不匹配");
            }
            for (TsListeningArticle article : articles) {
                ldmi.getArticleMap().put("a" + article.getArticleNum(), article);
                HashMap<String, Object> param = new HashMap<>();
                param.put(MAPPER_PARAM_SUBJECT_NAME, subjectName);
                param.put(MAPPER_PARAM_LISTENING_ARTICLE_ID, article.getId());
                List<TsListeningQuestion> questions = tsListeningQuestionsMapper.getQuestions(param);
                for (TsListeningQuestion question : questions) {
                    ldmi.getQuestionMap().put("a" + article.getArticleNum() + "-" + question.getQuestionNum(), question);
                }
            }
            saveSuccessMsgAndData(hrc, ldmi);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_single_data.do", method = RequestMethod.POST)
    public void getListeningSingleData(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                                       @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) String articleNum,
                                       HttpServletRequest request,
                                       HttpServletResponse response) {
        HttpResContent<ListeningDataMapInfo> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取听力数据");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum);
            // do
            Map<String, Object> params = new HashMap<>();
            params.put(MAPPER_PARAM_SUBJECT_NAME, subjectName);
            params.put(MAPPER_PARAM_ARTICLE_NUM, articleNum);
            TsListeningArticle article = tsListeningArticlesMapper.getBySubjectNameAndArticleNum(params);
            if (article == null) {
                throw new IllegalArgumentException("获取单题失败");
            }
            ListeningDataMapInfo ldmi = new ListeningDataMapInfo();
            ldmi.setSubjectName(subjectName);
            ldmi.getArticleMap().put("a" + article.getArticleNum(), article);
            HashMap<String, Object> param = new HashMap<>();
            param.put(MAPPER_PARAM_SUBJECT_NAME, subjectName);
            param.put(MAPPER_PARAM_LISTENING_ARTICLE_ID, article.getId());
            List<TsListeningQuestion> questions = tsListeningQuestionsMapper.getQuestions(param);
            for (TsListeningQuestion question : questions) {
                ldmi.getQuestionMap().put("a" + article.getArticleNum() + "-" + question.getQuestionNum(), question);
            }
            saveSuccessMsgAndData(hrc, ldmi);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 保存某一问题答案
     *
     * @param examinationId 考试ID
     * @param subjectName   套题名称
     * @param articleNum    文章序号
     * @param questionNum   问题序号
     * @param answer        答案:a,b
     * @param response      response
     */
    @RequestMapping(value = "/save_answer.do", method = RequestMethod.POST)
    public void saveAnswer(@RequestParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID) String examinationId,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) Integer articleNum,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM) Integer questionNum,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_ANSWER) String answer,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("答案保存");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum.toString());
            checkParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM, questionNum.toString());
            checkParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID, examinationId);
            // do.
            ExaminationInfo ei = SExaminationQueueCache.getInstance().getExaminationInfo(examinationId);
            ExamListeningInfo eli = ei.getExamListeningInfo();
            if (eli.getAnswerMap().get(articleNum).containsKey(questionNum)) {
                eli.getAnswerMap().get(articleNum).put(questionNum, answer);
                // log answer
                SysUtil.logExamRecordInfo(ei.getUserId(), examinationId, ExamContentTypeEnum.LISTENING, articleNum, questionNum, answer);
            }
            //// 每次更新答案, 都更新记录的最后访问时间, 以延长缓存时间
            ei.setLastUpdateTime(new Date());
            ei.setCurAnswerProcess(ExamContentTypeEnum.LISTENING, String.format("a%s-q%s", articleNum, questionNum));
            // 同步数据到MC
            SExaminationQueueCache.getInstance().syncDataToMC(examinationId, ei);
            // response.
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

}
